<template>
  <el-dialog width="960px"  class="packing"   title="打包" :close-on-click-modal="false"  :visible.sync="visible">


    <el-form :inline="true" class="demo-form-inline dabao" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item :label="pknum" class="qudao">
        <el-checkbox-group v-model="packed" @change="setCheckBox">
          <el-checkbox v-for="pack in packages" :label="pack.inTrackingNumber" :key="pack.inTrackingNumber">{{pack.inTrackingNumber}}[{{pack.shipping}}][{{pack.weight}}kg]</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="会员识别码" style="margin-bottom: 0">
        <el-tag style="margin-left: 0">{{dataForm.specialId}}</el-tag> 包裹订单号<el-tag>{{dataForm.orderSn}}</el-tag>收件人 <el-tag>{{dataForm.name}}</el-tag> 电话 <el-tag>{{dataForm.mobile}}</el-tag>邮编<el-tag>{{dataForm.zipcode}}</el-tag>
      </el-form-item>
      <el-form-item label="国家" style="width: 100%;margin-bottom: 0" >
        <el-tag style="margin-left: 0">{{dataForm.country}}</el-tag>  州/省 <el-tag>{{dataForm.province}}</el-tag> 城市 <el-tag>{{dataForm.city}}</el-tag>详细地址<el-tag>{{dataForm.address}}</el-tag>
      </el-form-item>
      <el-form-item label="包裹信息" style="width: 100%;">
        <el-tag style="margin-left: 0">.{{dataForm.packInfo}}</el-tag>客户留言<el-tag>.{{dataForm.postscript}}</el-tag>
      </el-form-item>


      <el-form-item label="重量/kg"  prop="weight" class="weight weight2">
        <el-input v-model="dataForm.weight" v-on:input="wartchNum" placeholder="重量/kg" ></el-input>
      </el-form-item>

      <el-form-item label="长" class="weight">
        <el-input v-model="dataForm.length" placeholder="长/cm"></el-input>
      </el-form-item>
      <el-form-item label="宽" class="weight">
        <el-input v-model="dataForm.width" placeholder="宽/cm" ></el-input>
      </el-form-item>
      <el-form-item label="高" class="weight">
        <el-input v-model="dataForm.height" placeholder="高/cm"></el-input>
      </el-form-item>
      <el-form-item v-if="isjisuan" label="可发渠道" style="width: 100%">
        输入重量,长宽高后计算
      </el-form-item>
      <el-form-item v-else label="可发渠道" class="qudao">

        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="city in cities" :label="city.shipping_name" :key="city.shipping_id">{{city.shipping_name}}[{{city.time}}][{{city.fee}}元]</el-checkbox>
        </el-checkbox-group>


      </el-form-item>

      <el-form-item label="客服号" prop="kefuId" >
        <el-select v-model="dataForm.kefuId" placeholder="请选择" clearable>
          <el-option
            v-for="item in kefuList"
            :key="item.userId"
            :label="item.realname"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理员备注"  prop="adminnote2">
        <el-input type="textarea" :rows="2" v-model="dataForm.adminnote2" placeholder="管理员备注" style="width: 300px"></el-input>
        <el-button @click="submitNote()" type="text">提交备注</el-button>
      </el-form-item>
      <!--      <el-form-item label="通知" prop="userCode" style="margin-bottom: 8px;width: 400px">-->
      <!--        <el-radio v-model="radio" label="1">顺利打包</el-radio>-->
      <!--        <el-radio v-model="radio" label="2">打包卡住</el-radio>-->
      <!--      </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" :disabled="isActive" @click="dataFormSubmit()">开始打包</el-button>
      <el-button @click="visible=false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        isIndeterminate: false,
        checkAll: false,
        isjisuan:true,
        isActive:true,
        kefuList:[],
        radio:'1',
        pknum:'包裹数量(14)',
        visible: false,
        dataForm: {
          orderId: 0,
          length:'',
          width:'',
          height:'',
          weight:'',
          kefuId:'',
          kefu:'',
          adminnote:'',
          adminnote2:''
        },
        packed: [],
        packages: [],
        checkedCities:[],
        checkedCities2:[],
        cities:[],
        dataRule: {
          kefuId: [
            { required: true, message: '请选择客服', trigger: 'change' }
          ],
          weight: [
            { required: true, message: '重量不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      submitNote() {
        let note=this.dataForm.adminnote2
        if(typeof (note)=='undefined'||note=='')return false
        let orderId=this.dataForm.orderId
        this.$http({
          url: this.$http.adornUrl('/order/v9order/savenote'),
          method: 'get',
          params: this.$http.adornParams({
            'order_id': orderId,
            'note':note
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '提交成功',
              type: 'success',
              duration: 800,
              onClose: () => {
                this.dataForm.adminnote2=''
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      handleCheckAllChange(val) {
        this.checkedCities = val ? this.checkedCities2 : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },
      setCheckBox(){
        if (this.packages.length==this.packed.length){
          this.isActive=false
        }else {
          this.isActive=true
        }
      },
      wartchNum(){
        this.isjisuan=false
        this.$http({
          url: this.$http.adornUrl(`/order/v9order/transport`),
          method: 'get',
          params: this.$http.adornParams({
            'region_id': this.dataForm.addId,
            'length': this.dataForm.length,
            'width': this.dataForm.width,
            'height': this.dataForm.height,
            'weight':this.dataForm.weight,
            'order_id': this.dataForm.orderId,
            'region_id':16
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.cities=data.info;
            let info=data.info;
            let checked=[];
            for(let i=0;i<info.length;i++){
              checked.push(info[i]['shipping_name'])
            }
            //this.checkedCities=checked
            this.checkedCities2=checked
          } else {
            //this.$message.error(data.msg)
          }
        })
      },
      initScannerModule(){
        let lastTime = null;
        let nextTime = null;
        let code = '';
        let that=this;
        document.onkeydown = function (e) {
          let keycode = e.keyCode || e.which || e.charCode;
          nextTime = new Date();
          if (keycode === 13) {
            if (lastTime && (nextTime - lastTime < 30)) {
              // 扫码枪
              // do something
              //console.log(code+"扫码枪")
              that.dataForm.inTrackingNumber=code;
            } else {
              // 键盘
              // do something
              //that.dataForm.inTrackingNumber=code;
            }
            let packages=that.packages;
            for(let i=0;i<packages.length;i++){
              let number=packages[i]['inTrackingNumber'];
              if(code==number){
                that.packed.push(number)
              }
            }
            if (that.packages.length==that.packed.length){
              that.isActive=false
            }
            code = '';
            lastTime = null;
            e.preventDefault();
          } else {
            if (!lastTime) {
              code = String.fromCharCode(keycode);
            } else {
              if (nextTime - lastTime < 30) {
                code += String.fromCharCode(keycode);
              } else {
                code += String.fromCharCode(keycode);
              }
            }
            lastTime = nextTime;
          }
        };
      },
      init (id) {
        this.isActive=true
        this.checkedCities=[]
        this.cities=[]
        this.packed=[]
        this.packages=[]
        this.initScannerModule()
        this.dataForm.orderId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.orderId) {
            this.$http({
              url: this.$http.adornUrl(`/order/v9order/info/${this.dataForm.orderId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.shippingId = data.v9Order.shippingId
                this.dataForm.data = data.v9Order.data
                this.dataForm.orderSn = data.v9Order.orderSn
                this.dataForm.uid = data.v9Order.uid
                this.dataForm.specialId = data.v9Order.specialId
                this.dataForm.servicesFee = data.v9Order.servicesFee
                this.dataForm.integral = data.v9Order.integral
                this.dataForm.postscript = data.v9Order.postscript
                this.dataForm.addId = data.v9Order.addId
                this.dataForm.addservices = data.v9Order.addservices
                this.dataForm.name = data.v9Order.name
                this.dataForm.country = data.v9Order.country
                this.dataForm.mobile = data.v9Order.mobile
                this.dataForm.city = data.v9Order.city
                this.dataForm.province = data.v9Order.province
                this.dataForm.zipcode = data.v9Order.zipcode
                this.dataForm.address = data.v9Order.address
                this.dataForm.additional = data.v9Order.additional
                this.dataForm.discount = data.v9Order.discount
                this.dataForm.extras = data.v9Order.extras
                this.dataForm.adminnote = data.v9Order.adminnote
                this.dataForm.packInfo = data.v9Order.packInfo
                this.dataForm.kefuId = data.v9Order.kefuId
                this.dataForm.detain = data.v9Order.detain
                this.dataForm.pOrderId = data.v9Order.pOrderId
                this.packages=data.data.packages
                this.kefuList=data.kefu
                this.pknum='包裹数量('+data.data.packages.length+')'
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        let kefuId=this.dataForm.kefuId
        var obj=this.kefuList.find(function (obj) {
          return obj.userId === kefuId
        })
        let kefu=obj.realname;
        if (this.isActive)return false
        // if(this.checkedCities.length>1) {
        //   this.$message('只能选择一个发货渠道')
        //   return false
        // }
        // let c=this.checkedCities[0]
        // let index = this.cities.findIndex(function(item) {
        //   return item.shipping_name === c
        // });
        let checkedCitisArr=this.checkedCities
        let fee_dataArr=[]
        for(let i=0;i<checkedCitisArr.length;i++){
          let c=checkedCitisArr[i]
          let index = this.cities.findIndex(function(item) {
            return item.shipping_name === c
          });
          fee_dataArr.push(this.cities[index])
        }

        let fee_data=JSON.stringify(fee_dataArr)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/order/v9order/dabao`),
              method: 'post',
              data: this.$http.adornData({
                'order_id':this.dataForm.orderId,
                'length':this.dataForm.length,
                'width':this.dataForm.width,
                'height':this.dataForm.height,
                'weight':this.dataForm.weight,
                'kefuId':this.dataForm.kefuId,
                'kefu':kefu,
                'adminnote':this.dataForm.adminnote2,
                'fee_data':fee_data
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .packing .el-checkbox-group .el-checkbox{
    margin-left: 0;
    margin-right: 30px;
    line-height: 30px;
  }
  .packing .el-checkbox-group{
    line-height: 30px;
  }
  .firstlabel .el-form-item__label{
    line-height: 30px;
  }

  .weight label{
    width: 30px !important;
  }
  .weight{
    width: 135px !important;
  }
  .weight .el-input{
    width: 100px !important;
  }
  .weight2 label{
    width: 100px !important;
  }
  .weight2{
    width: 210px !important;
  }
  .qudao .el-form-item__content{
    width: 750px;
  }
  .qudao{
    width: 100%;
    display: flex !important;
    justify-content: flex-start
  }
  .packing .el-tag{
    margin-right: 10px;
    margin-left: 10px;
  }

</style>
